import {
	defineStore
} from 'pinia'
import * as API from "../api/api.js"
import { Base64 } from 'js-base64';
// import { useChatStore } from "./chat.js"
// const useChatData = useChatStore()
export const userLoginStore = defineStore('userLogin', {
  unistorage: true, // 是否持久化到内存
	state: () => {
		return {
      token: null,
      accountId: null,
      userInfo: null,
			redirectUrl: "/pages/chat/chat",
      loginType: "wx"
		}
	},
	actions: {
    setRedirectUrl(redirectUrl) {
      this.redirectUrl = redirectUrl || "/pages/chat/chat"
    },
    // 登录日志
    saveAccountLog() {
      uni.getSystemInfo({
        success: (res) => {
        let params = {
            accountId: this.userInfo.accountId,
            brand: res.brand,
            model: res.model,
            wechatVersion: res.version,
            systemVersion: res.system,
            sdkVersion: res.SDKVersion,
            loginType: this.loginType
          }
          API.accountLog(params).then(res => {
            if (res.code === 0){
              console.log("登录日志调用成功")
            }
          }).catch(err => {
            
          })

        }
      })
    },
    // token解析
    analyzeToken(token) {
      this.token = token
      let wxUserInfoSync = JSON.parse(Base64.decode(token?.split('.')[1]))
      if (!wxUserInfoSync) return
      this.accountId = wxUserInfoSync.accountId
      uni.setStorageSync('token', this.token);
      this.getUserInfoData().then(res => {
        uni.redirectTo({
          url: this.redirectUrl ? this.redirectUrl : "/pages/chat/chat"
				});
				setTimeout(() => {
					this.redirectUrl = "/pages/chat/chat"
				}, 1500)
      })
    },
    // 微信登陆
    handleWxLogin(){
      uni.login({
        provider: "weixin",
        success: res=>{
          console.log("微信登陆code-------", res)
          // this.getOpenId(res.code)
        },
        fail: err=>{

        }
      })
    },

    //授权手机号登陆获取数据
    getOpenIdLogin(code, obj) {
      this.loginType = "wx"
      API.getOpenIdLogin({code}).then(res => {
        if (res.code === 0){
          this.getTokenByOpenId({...res.data, ...obj})
        }
      }).catch(err => {
        uni.showToast({
          title: err?.data?.message || "解析openId失败",
          icon: "none"
        })
      })
    },

    // 获取openId
    getOpenId(code) {
      return new Promise((resolve, reject)=>{
        API.getOpenId({code}).then(res => {
          if (res.code === 0){
            this.token = res.data.token
            let wxUserInfoSync = JSON.parse(Base64.decode(res.data.token?.split('.')[1]))
            if (!wxUserInfoSync) return
            this.accountId = wxUserInfoSync.accountId
            uni.setStorageSync('token', this.token);
            resolve()
          } else {
            uni.clearStorageSync()
            reject()
          }
        }).catch(err => {
          uni.clearStorageSync()
          reject()
        })
      })
    },

    // 获取token 
    getTokenByOpenId(params) {
      API.getTokenByOpenId(params).then(res => {
        if (res.code === 0) {
          this.analyzeToken(res.data)
        }
      }).catch(err => {
        uni.showToast({
          title: err?.data?.message || "获取token失败",
          icon: "none"
        })
      })
    },

    // 验证码
    getTelCodeNum(code) {
      API.getTelCode(code).then(res => {

      }).catch(err => {
        console.log("接口请求错误", err)
        uni.showToast({
          title: err?.data?.message || "获取验证码失败",
          icon: "none"
        })
      })
    },
    // 获取token并解析  
    getUserPhoneNumber(code) {
      API.getUserPhoneNumber(code).then(res => {
        if (res.code == 0) {
          this.token = res.data
          let wxUserInfoSync = JSON.parse(Base64.decode(res.data?.split('.')[1]))
          if (!wxUserInfoSync) return
          this.accountId = wxUserInfoSync.accountId
          uni.setStorageSync('token', this.token);
          this.getUserInfoData().then(res => {
            uni.redirectTo({
							url: this.redirectUrl ? this.redirectUrl : "/pages/chat/chat"
						});
						setTimeout(() => {
							this.redirectUrl = "/pages/chat/chat"
						}, 1500)
          })
        }
      }).catch(err => {
        console.log("接口请求错误", err)
        uni.showToast({
          title: err?.data?.message,
          icon: "none"
        })
      })
    },
    // 获取用户信息
    getUserInfoData(accountId) {
      return API.getUserInfo(accountId || this.accountId).then(res => {
        if (res.code == 0) {
          console.log("用户", res)
          res.data.customers.gender = res.data?.customers?.gender ? res.data?.customers?.gender : 1
          res.data.customers.headUrl = res.data?.customers?.headUrl ? res.data?.customers?.headUrl : "https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/avart-wu.png"
          this.userInfo = res.data
          uni.setStorageSync('userInfo', JSON.stringify(res.data));
          this.initPresetQuestion()
          this.saveAccountLog()
        }
      }).catch(err => {
        console.log("接口请求错误", err)
        uni.showToast({
          title: err?.data?.message || "获取用户信息失败",
          icon: "none"
        })
      })
    },

    // 手机号验证码登陆
    handleTelCodeLogin(value) {
      this.loginType = "mobile"
      return API.telCodeLogin(value).then(res => {
        if (res.code == 0) {
          console.log("登陆成功", res)
          this.token = res.data
          let wxUserInfoSync = JSON.parse(Base64.decode(res.data?.split('.')[1]))
          if (!wxUserInfoSync) return
          this.accountId = wxUserInfoSync.accountId
          uni.setStorageSync('token', this.token);
          this.getUserInfoData().then(res => {
            uni.redirectTo({
							// url: "/pages/chat/chat"
							url: this.redirectUrl ? this.redirectUrl : "/pages/chat/chat"
						});
						setTimeout(() => {
							this.redirectUrl = "/pages/chat/chat"
						}, 1500)
          })
        }
      }).catch(err => {
        console.log("接口请求错误", err)
        uni.showToast({
          title: err?.data?.message,
          icon: "none"
        })
      })
    },
    // 保存用户信息
    saveUserInfoData(userInfo) {
      console.log("usreInfo", userInfo)
      return API.saveUserInfo(userInfo).then(res => {
        if (res.code == 0) {
          this.userInfo = res.data
          return res
        }
      }).catch(err => {
        console.log("接口请求错误", err)
        uni.showToast({
          title: err?.data?.message || "保存用户信息失败",
          icon: "none"
        })
      })
    },

    initPresetQuestion() {
      this.userInfo = uni.getStorageSync("userInfo") ? JSON.parse(uni.getStorageSync("userInfo")) : null
      return API.initPresetQuestion({userId: this.userInfo?.customers?.customerId}).then(res => {
        if (res.code === 0) {
          console.log("初始化成功")
        }
      }).catch(err => {

      })
    }
  }
})

